$(function() {
	$('#new_item_button').button({icons:{primary:'ui-icon-plusthick'}});

	$('input#search_box').autocomplete({
		source: function(request, response) {
			$.ajax({
				type: 'post',
				url: 'inventory/item_autocomplete/',
				data: {
					term: request.term
				},
				dataType: 'json',
				success: response
			});
		},
		select: function( event, ui ) {
			$('#inv_div').load('inventory/item_search/'+ui.item.id , function(){
				$('#search_box').val('');
				$('.inv_pagination').empty();
			});
		}
	});

	$('#new_item_button').click(function(e){
		e.preventDefault();
		$('#edit_item_modal').empty();
		$('#new_item_modal').load($(this).attr('href'), function() {
			$(this).dialog('open');
		});
	});

	$("#new_item_modal").dialog({
		autoOpen: false,
		modal: true,
		title: 'New Item',
		minWidth: 350,
		resizable:false,
		buttons: {
			Add: function() {
				$("#new_item_modal form").submit();
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});

	$('.edit_item_button').livequery('click', function(e) {
		e.preventDefault();
		$('#new_item_modal').empty();
		$('#edit_item_modal').load($(this).attr('href'), function() {
			$(this).dialog('open');
		});
	});

	$("#edit_item_modal").dialog({
		autoOpen: false,
		modal: true,
		title: 'Edit Item',
		minWidth: 350,
		resizable:false,
		buttons: {
			Update: function() {
				$("#edit_item_modal form").submit();
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});

	$('.inv_button').livequery('click',function(e){
		e.preventDefault();
		$('#inv_modal').load($(this).attr('href'), function() {
			$(this).dialog('open');
		});
	});

	$("#inv_modal").dialog({
		autoOpen: false,
		modal: true,
		title: 'Inventory',
		minWidth: 350,
		resizable:false,
		buttons: {
			Update: function() {
				$("#inv_modal form").submit();
			},
			Cancel: function(){
				$(this).dialog("close");
			}
		}
	});

	$('.delete_item_button').livequery('click', function(e) {
		e.preventDefault();
		var pop = confirm('Are you sure you want to delete this?');
		if(pop) {
			$.get($(this).attr('href'), function() {
				inv_pagination_init();
			});
		}
	});

	$('#refresh_items').livequery('click', function(e){
		e.preventDefault();
		inv_pagination_init();
	});
});

function inv_pagination_init()
{
	$(".inv_pagination").pagination(inv_num_entries, {
        num_edge_entries: inv_num_edge_entries,
		num_display_entries: 5,
        callback: function(idx, jq) {
			$.ajax({
				url: 'inventory/inv_tbl/' + idx,
				type: 'post',
				success: function(response) {
					$('#inv_div').html(response);
				}
			});
		},
        items_per_page: inv_items_per_page
    });
}